﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.LinqToSqlProvider;

namespace Akronus.TaskScheduler.LinqDataService
{
    public class TaskInfoDataService : Repository, ITaskInfoDataService
    {
        public void SaveTaskInfo(TaskInfo taskLog)
        {
            using (var contextManager = CreateContextManager(false))
            {
                var taskInfo = contextManager.Context.TaskInfos().FirstOrDefault(t => t.Name == taskLog.Name);
                if (taskInfo == null)
                {
                    contextManager.Context.TaskInfos().InsertOnSubmit(taskLog);
                }
                else
                {
                    taskInfo.Data = taskLog.Data;
                    taskInfo.LastRunTime = taskLog.LastRunTime;
                    taskInfo.Status = taskLog.Status;
                }
                contextManager.Commit();
            }
        }

        public IList<TaskInfo> GetTaskInfos()
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.TaskInfos().ToList();
            }
        }

        public TaskInfo GetTaskInfo(string taskName)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.TaskInfos().FirstOrDefault(t => t.Name == taskName);
            }
        }

        public IList<TaskInfo> GetTaskInfos(string taskType)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.TaskInfos().Where(t => t.Type == taskType).ToList();
            }
        }
    }
}
